#pragma once
#include "Epoller.hpp"
#include "Socket.hpp"
#include "log.hpp"
#include <iostream>
#include <memory>
#include <string>

const static uint16_t defaultport = 8888;
uint32_t EVENT_IN = (EPOLLIN);
uint32_t EVENT_OUT = (EPOLLOUT);

class EpollServer: public nocopy
{
    const static int num = 64;
public:
    EpollServer(uint16_t port = defaultport)
        :_port(port)
        ,_listensocket_ptr(std::make_shared<Sock> ())
        ,_epoller_ptr(std::make_shared<Epoller> ())
    {}
    void Init()
    {
        _listensocket_ptr->Socket();
        _listensocket_ptr->Bind(_port);
        _listensocket_ptr->Listen();
        LOG(Info, "create listen socket success: %d", _listensocket_ptr->GetFd());
    }
    void Start()
    {
       // 将listenfd添加到Epoll中--> listenfd和它关心的事件添加到内核epoll模型中的rbTree
       // epoll_ctl(_epfd, EPOLL_CTL_ADD, _listensocket_ptr->GetFd(), EPOLLIN); 
       _epoller_ptr->EpollUpdate(EPOLL_CTL_ADD, _listensocket_ptr->GetFd(), EVENT_IN);
       struct epoll_event revs[num];
       for(;;)
       {
            int n = _epoller_ptr->EpollWait(revs, num);
            if (n > 0) {
                // 有事件就绪
                LOG(Debug, "event happened, fd is: %d", revs[0].data.fd);
                Dispathcer(revs, n);
            }
            else if (n == 0) {
                LOG(Info, "time out...");
            }
            else {
                LOG(Error, "epoll wait error");
            }
       }
    }
    void Dispathcer(struct epoll_event revs[], int num)
    {
        for (int i = 0; i < num; ++i)
        {
            uint32_t events = revs[i].events;
            int fd = revs[i].data.fd;
            if (events &EVENT_IN) {
                if (fd == _listensocket_ptr->GetFd()) {
                    Accepter();
                }
                else {
                    Recver(fd);
                }
            }
            else if (events & EVENT_OUT) {

            }
            else {

            }
        }
    }
    void Accepter()
    {
        std::string clientip;
        uint16_t clientport;
        int sock = _listensocket_ptr->Accept(&clientip, &clientport);
        if (sock > 0) {
            _epoller_ptr->EpollUpdate(EPOLL_CTL_ADD, sock, EVENT_IN);
            LOG(Info, "Get a new link, client: %s:%d", clientip.c_str(), clientport);
        }
    }
    void Recver(int sockfd)
    {
        char buffer[1024];
        ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
        if (n > 0) {
            buffer[n] = 0;
            std::cout << "get a message: " << buffer << std::endl;
            
            std::string echo = "server echo $";
            echo += buffer;
            write(sockfd, echo.c_str(), echo.size());
        }
        else if (n == 0) {
            LOG(Info, "client quit, close fd is: %d", sockfd);
            // 需要先DEL再close,否则访问无效资源,报错
            _epoller_ptr->EpollUpdate(EPOLL_CTL_DEL, sockfd, 0);
            close(sockfd);
        }
        else {
            LOG(Warning, "recv error, sockfd is: %d", sockfd);
            // 需要先DEL再close,否则访问无效资源,报错
            _epoller_ptr->EpollUpdate(EPOLL_CTL_DEL, sockfd, 0);
            close(sockfd);
        }
    }
private:
    uint16_t _port;
    std::shared_ptr<Sock> _listensocket_ptr;
    std::shared_ptr<Epoller> _epoller_ptr;
};